package com.mingxingyi.base.exception.handle;


import com.mingxingyi.base.exception.obj.BaseException;
import com.mingxingyi.base.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

@ControllerAdvice
@Slf4j
//确保返回的是数据，而不是视图
@ResponseBody
public class GlobalExceptionHandling extends ResponseEntityExceptionHandler {


    @ExceptionHandler(Exception.class)
    public ResultVO<Object> handleAllExceptions(Exception ex) {
        log.error("", ex);
        if (ex instanceof BaseException) {
            BaseException baseException = (BaseException) ex;
            return ResultVO.fail(baseException.getCode(), baseException.getMessage());
        } else if (ex instanceof MethodArgumentNotValidException) {
            // @Valid异常处理
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) ex;
            BindingResult exceptions = validException.getBindingResult();
            if (exceptions.hasErrors()) {
                List<ObjectError> errors = exceptions.getAllErrors();
                if (!errors.isEmpty()) {
                    FieldError fieldError = (FieldError) errors.get(0);
                    return ResultVO.fail(fieldError.getDefaultMessage());
                }
            }
        }
        return ResultVO.fail(ex.getMessage());
    }

}
